#include "MyThreadPool.h"

struct ThreadNode
{
	GCoptimizationGeneralGraph* gc;
	CGraphFitting* gf;
	MyThreadPool* mtp;
};
void threadFun( void* param ) 
{
	ThreadNode* tn=(ThreadNode*)param;
	while(!tn->mtp->finishAllTask())
	{
		int lineID=tn->mtp->fetchTask();
		if(lineID<0)	
			break;
		else	
		{
			tn->gf->fitLine(lineID,tn->gc);
		}
	}
	_endthread();
}

MyThreadPool::MyThreadPool(int threadNumber)
{
	InitializeCriticalSection(&cs);
	numThreads=threadNumber;
}
void  MyThreadPool::startThreads(GCoptimizationGeneralGraph* _gc,CGraphFitting* _gf)
{
	ThreadNode node;
	node.gc=_gc;node.gf=_gf;node.mtp=this;
	for(int i=0;i<numThreads;++i)
	{
		handleArray[i]=(HANDLE)_beginthread(threadFun,0,&node);
	}
	printf("start working threads\n");
}
MyThreadPool::~MyThreadPool(void)
{
	DeleteCriticalSection(&cs);
}
int MyThreadPool::fetchTask()
{
	EnterCriticalSection(&cs);
	if(Q.empty())	
	{
		LeaveCriticalSection(&cs);
		return -1;
	}
	int val=Q.front();
	Q.pop();
	LeaveCriticalSection(&cs);
	return val;
}
void MyThreadPool::waitForThreads()
{
	WaitForMultipleObjects(numThreads,handleArray,TRUE,INFINITE);
	printf("All Threads Finish\n");
}
